<?php
switch ($action) {
	case 'showIndex':
		$totalsize = 0;
        $data = new Data();
		$dataTable = $data->showTable();
        foreach ($dataTable AS $key=>$value){
			$size = $value['Data_length'] + $value['Index_length'];
			$totalsize += $size;
			$free = $value['Data_free'] ? number_format($value['Data_free'] / 1024, 2) . 'K' : '';
			$table[] = array('name' => $value['Name'], 'row' => $value['Rows'], 'size' => number_format($size / 1024, 2), 'free' => $free);
        }
		$totalsize = number_format($totalsize / (1024 * 1024), 2);
		include template('admin/data');
		break;
	case '_export':
        $fileid = intval(_g('fileid'));
		$fileid = !empty($fileid) ? $fileid : 1;
		if ($fileid == 1) {
            $selids = _g('selids');
			if ($selids == '') redirect('./data.php?action=showIndex',2,'请选择要备份的数据表!');
			$random = mt_rand(1000, 9999);
			$tables = explode(',', $selids);
			cache_write('tmp_bakup_tables', $tables);
		} else {
			$tables = cache_read('tmp_bakup_tables');
			if (!$tables) redirect('./data.php?action=showIndex',2,'请选择要备份的数据表!');
		}
		$sqldump = '';
        $tableid = trim(_g('tableid'));
		$tableid = !empty($tableid) ? $tableid - 1 : 0;
        $startfrom = trim(_g('startfrom'));
		$startfrom = isset($startfrom) ? intval($startfrom) : 0;
        $tables = _g('tables');
		$tablenumber = count($tables);
        $sizelimit = intval(_g('sizelimit'))?intval(_g('sizelimit')):2048;
        $backname = trim(_g('backname'));
		for($i = $tableid; $i < $tablenumber && strlen($sqldump) < $sizelimit * 1000; $i++) {
			$sqldump .= sql_dumptable($tables[$i], $startfrom, strlen($sqldump));
			$startfrom = 0;
		}
		if (trim($sqldump)) {
			$sqldump = "#/**\n#happyCms 数据备份\n#此备份版权归HappyCMS版权所有# --------------------------------------------------------\n#**/\n\n\n" . $sqldump;
			$tableid = $i;
			$filename = $backname . '_' . date('Ymd') . '_' . $random . '_' . $fileid . '.sql';
			$fileid++;

			$bakfile = './database/' . $filename;
            $forward = trim(_g('forward'));
			if (!is_writable('./database/')) redirect($forward,2,'数据无法备份到服务器!请检查 ./data 目录是否可写。');
			file_put_contents($bakfile, $sqldump);
			redirect('?action=' . $action . '&backname=' . $backname . '&sizelimit=' . $sizelimit . '&tableid=' . $tableid . '&fileid=' . $fileid . '&startfrom=' . $startrow . '&random=' . $random, 2, "备份文件 $filename 写入成功!" );
		} else {
			cache_delete('tmp_bakup_tables');
			redirect('./data.php?action=import',2,'表备份成功');
		}
		break;
	case 'query':
		include template('admin/data');
		break;
	case '_query':
		if (!$config['runsql']) redirect('./data.php?action=showIndex',2,'返回数据库管理页');
        $sql = _g('sql');
		$sql = stripslashes($sql);
		if (trim($sql) != ''){
            $data = new Data();
            $data -> tableQuery($sql);
        }
		redirect('./data.php?action=query',2,'语句执行成功');
		break;
	case 'import':
		$sqlfiles = glob('./database/*.sql');
		if (is_array($sqlfiles)) {
			$prepre = '';
			$info = $infos = array();
			foreach($sqlfiles as $id => $sqlfile) {
				$pathinfo = pathinfo($sqlfile);
				preg_match("/([a-z0-9_]+_[0-9]{8}_[0-9a-z]{4}_)([0-9]+)\.sql/i", $pathinfo['basename'], $num);
				isset($num[0]) or $num = array($pathinfo['filename'], $pathinfo['filename'], 0);
				$info['filename'] = $num[0];
				$info['file'] = substr(basename($sqlfile), 0, -4);
				$info['filesize'] = round(filesize($sqlfile) / (1024 * 1024), 2);
				$info['maketime'] = date('Y-m-d H:i:s', filemtime($sqlfile));
				$info['pre'] = $num[1];
				$info['number'] = $num[2];
				$infos[] = $info;
			}
		}
		include template('admin/data');
		break;
	case '_import':
        $fileid = intval(_g('fileid'));
		$fileid = !empty($fileid) && $fileid > 0 ? $fileid : 1;
        $pre =trim(_g('pre'));
		$filename = $pre . $fileid . '.sql';
		$filepath = './database/' . $filename;
		if (file_exists($filepath)) {
			$sql = file_get_contents($filepath);
            $data = new Data();
            $data -> tableQuery($sql);
			$fileid++;
            redirect("?file=data&action=_import&pre=" . $pre . "&fileid=" . $fileid,2,"数据文件 $filename 导入成功!");
		}else{
            redirect("?file=data&action=import",2,"返回数据库管理页");
        }
		break;
	case 'del':
        $pre =trim(_g('pre'));
		$sqlfiles = glob(DIR_ROOT . '/'.$config['manage'].'/data/database/' . $pre . '*.sql');
		if ($pre && is_array($sqlfiles)) {
			foreach($sqlfiles as $sqlfile) {
				@unlink($sqlfile);
			}
            redirect('./data.php?action=import', 2 , '数据库删除成功');
		} else redirect('./data.php?action=import', 2 , '数据库删除失败');;
		break;
	case 'down':
        $filename =trim(_g('filename'));
		$filename or redirect('./data.php?action=showIndex',2,'文件名不能为空');
		file_down(DIR_ROOT . '/'.$config['manage'].'/data/database/' . $filename . '.sql');
		break;
	case 'repair':
        $selids = trim(_g('selids'));
        $operation = trim(_g('operation'));
		if ($selids && in_array($operation, array('repair', 'optimize'))){
            $data = new Data();
            $data -> tableQuery("$operation TABLE $selids");
        }
		redirect('./data.php?action=showIndex', 2 , '数据库修复成功');
		break;
	default :
		redirect('./data.php?action=showIndex',2,'返回数据库管理页');
		break;
}
function sql_dumptable($table, $startfrom = 0, $currsize = 0) {
	global $sizelimit;
    $startrow = intval(_g('startrow'));
	if (!isset($tabledump)) $tabledump = '';
	$pagesize = 100;
    $data = new Data();
	if (!$startfrom) {
        $create = $data->dropTable($table);
		$tabledump = "DROP TABLE IF EXISTS $table;\n";
		$tabledump .= $create[1] . ";\n\n";
	}
	$tabledumped = 0;
	$numrows = $pagesize;
	while ($currsize + strlen($tabledump) < $sizelimit * 1000 && $numrows == $pagesize) {
		$tabledumped = 1;
		$numfields = $data-> num_fields($table,$startfrom, $pagesize);
		$numrows = $data-> num_rows($table,$startfrom, $pagesize);
        $row = $data->tableRow($table,$startfrom, $pagesize);
		foreach ($row AS $key=>$value) {
			$comma = "";
			$tabledump .= "REPLACE INTO $table VALUES(";
			for($i = 0; $i < $numfields; $i++) {
				$tabledump .= $comma . "'" . mysql_escape_string($value[$i]) . "'";
				$comma = ",";
			}
			$tabledump .= ");\n";
		}
		$startfrom += $pagesize;
	}
	$startrow = $startfrom;
	$tabledump .= "\n";
	return $tabledump;
}



?>